//
//  KlineViewController.swift
//  Exchange
//
//  Created by rui on 2018/4/28.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class KlineViewController: BaseViewController {
    
    @IBOutlet weak var lastPrice: UILabel!
    @IBOutlet weak var exchangeLastPrice: UILabel!
    
    @IBOutlet weak var increase: UILabel!
    @IBOutlet weak var high: UILabel!
    @IBOutlet weak var low: UILabel!
    @IBOutlet weak var volume: UILabel!
    
    @IBOutlet weak var topContentView: UIView!
    @IBOutlet weak var bottomContentView: UIView!
    @IBOutlet weak var chatView: CHKLineChartView!
    
    @IBOutlet var timesArray: [KlineSelectButton]!
    @IBOutlet weak var sell: UIButton!
    @IBOutlet weak var buy: UIButton!
    
    
    @IBOutlet weak var btn1: KlineSelectButton!
    @IBOutlet weak var btn2: KlineSelectButton!
    @IBOutlet weak var btn3: KlineSelectButton!
    @IBOutlet weak var btn4: KlineSelectButton!
    @IBOutlet weak var btn5: KlineSelectButton!
    
    @IBOutlet weak var activityView: UIActivityIndicatorView!
    
    lazy var viewModel: KlineViewModel = KlineViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initBtns()
        initUI()
        initData()
    }
    
    func initData() {
        viewModel.peroid = "15" + kText("分")
        self.reloadInterface()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        viewModel.delegate = self
        viewModel.loadData()
        let period = viewModel.peroid
        viewModel.peroid = ""
        for btn in timesArray {
            if btn.title == period {
                self.timeClick(btn: btn)
            }
            btn.click = {[weak self](btn) in
                self?.timeClick(btn: btn)
            }
        }
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
         viewModel.clean()
    }
    
    
    func initBtns() {
        self.btn1.title = kText("分时")
        self.btn2.title = "15" + kText("分")
        self.btn3.title = "1" + kText("小时")
        self.btn4.title = "4" + kText("小时")
        self.btn5.title = kText("日线")
    }
    
    func initUI() {
        
        self.topContentView.themeBackground = ThemeManager.ThemeColorKeys.background
        self.bottomContentView.themeBackground = ThemeManager.ThemeColorKeys.background

        var items = self.navigationItem.leftBarButtonItems
        var name = viewModel.coinModel.name
        name = name.count > 0 ? name : "--/--"
        let title = UIBarButtonItem(title: name, style: .plain, target: self, action: #selector(goback))
        items?.append(title)
        self.navigationItem.leftBarButtonItems = items
    
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "goto_landscape"), style: .plain, target: self, action: #selector(gotoLandscape))
        
        chatView.delegate = self
        if ThemeManager.default.currentThemeMode() == .day {
            chatView.style = CHKLineChartStyle.customLight
        }else {
            chatView.style = CHKLineChartStyle.customDark
        }
        buy.layer.cornerRadius = 3
        buy.layer.masksToBounds = true
        buy.backgroundColor = kGreenColor
        sell.layer.cornerRadius = 3
        sell.backgroundColor = kRedColor
        sell.layer.masksToBounds = true
    }
    
    @IBAction func buy(_ sender: UIButton) {
        exchange(type: 0)
    }
    
    @IBAction func sell(_ sender: UIButton) {
        exchange(type: 1)
    }
    
    func exchange(type: Int) {
        let isSupport =  APPTransactionPair.default.checkCurrentIsSupportCoin(name: viewModel.coinModel.name)
        if !isSupport {
            CYMBShow.showMessage("当前币对不支持币币交易")
            return
        }
        guard let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else { return }
        guard let vc = tab.viewControllers?[1] as? NavigationController else {
            return
        }
        APPTransactionPair.default.selectPairModel = viewModel.coinModel 
        self.navigationController?.popToRootViewController(animated: false)
        tab.selectedIndex = 1
        guard let exchangeVc = vc.rui_topViewController as? CurrencyExchangeViewController else { return }
        exchangeVc.clearDepth()
        if type == 1 {
            exchangeVc.currencyView.sellAction(true)
        }else {
            exchangeVc.currencyView.buyBtnAction(true)
        }
    }
    
    @objc func gotoLandscape() {
        let LandscapeVC = KlineLandscapeViewController()
        LandscapeVC.fromViewController = self
        LandscapeVC.viewModel = self.viewModel
        self.present(LandscapeVC, animated: true, completion: nil)
    }
    
    @objc func goback() {
        self.navigationController?.popViewController(animated: true)
    }
    
    deinit {
       
    }
    
    
}


extension KlineViewController : CHKLineChartDelegate {
    
    func numberOfPointsInKLineChart(chart: CHKLineChartView) -> Int {
        return viewModel.dataArray.count
    }
    
    func kLineChart(chart: CHKLineChartView, valueForPointAtIndex index: Int) -> CHChartItem {
        let data = viewModel.dataArray[index]
        let item = CHChartItem()
        item.openPrice = CGFloat(data[0])
        item.closePrice = CGFloat(data[1])
        item.highPrice = CGFloat(data[2])
        item.lowPrice = CGFloat(data[3])
        item.vol = CGFloat(data[4])
        item.time = Int(data[5])
        return item
    }
    
    func kLineChart(chart: CHKLineChartView, labelOnYAxisForValue value: CGFloat, atIndex index: Int, section: CHSection) -> String {
        var strValue = ""
        if section.key == "volume" {
            if value / 1000 > 1 {
                strValue = (value / 1000).ch_toString(maxF: section.decimal) + "K"
            } else {
                strValue = value.ch_toString(maxF: section.decimal)
            }
        } else {
            strValue = value.ch_toString(maxF: section.decimal)
        }

        return strValue
    }
    
    func kLineChart(chart: CHKLineChartView, labelOnXAxisForIndex index: Int) -> String {
        let data = viewModel.dataArray[index]
        let timestamp = Int(data[5])
        let dayText = Date.ch_getTimeByStamp(timestamp, format: "MM/dd HH:mm")
        return dayText
    }
    
    func kLineChart(chart: CHKLineChartView, decimalAt section: Int) -> Int {
        if section == 0 {
            return 8
        } else {
            return 2
        }
    }
    ///当前选中
    func kLineChart(chart: CHKLineChartView, didSelectAt index: Int, item: CHChartItem) {

    }
    
    ///切换分区的k线类型
    func kLineChart(chart: CHKLineChartView, didFlipPageSeries section: CHSection, series: CHSeries, seriesIndex: Int) {
    }
    
}

extension KlineViewController {
    
    @objc func timeClick(btn: KlineSelectButton) {
        if btn.title != kText("更多") {
            for view in timesArray {
                view.isSelected = false
            }
            btn.isSelected = true
        }
        
        if btn.buttonType != .normal {
            //处理更多弹框
            guard let view = KlineSelectView.loadFromNib() as? KlineSelectView else {return}
            view.buttonClick = {[weak view] subBtn in
                self.moreClick(period: subBtn.titleLabel!.text!, popView: view!)
            }
            let rect = btn.convert(btn.bounds, to: nil)
            let pop = PopView(contentView: view)
            pop.delegate = self
            btn.backgroundColor = view.backgroundColor
            pop.enableAnyTouchDissmiss()
            pop.hubColor = UIColor.clear
            if ((self as? KlineLandscapeViewController) != nil) {
                 let rect = btn.convert(btn.bounds, to: nil)
                var x:CGFloat = 0.0
                if #available(iOS 11.0, *) {
                    x = self.view.safeAreaInsets.left
                } else {
                    // Fallback on earlier versions
                }
                view.addShadow(shadowOffset: CGSize(width: 0, height: -3))
                pop.pop(inRect: CGRect(x: x, y: rect.minY - 50 , width: max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) - x, height: 50))
            }else {
                view.addShadow(shadowOffset: CGSize(width: 0, height: 3))
                pop.pop(inRect: CGRect(x: 0, y: rect.maxY , width: kSCREEN_WIDTH, height: 50))
            }
        }else {
            
            for btn in self.timesArray {
                if btn.buttonType != .normal {
                    btn.title = kText("更多")
                }
            }
            self.activityView.startAnimating()
            viewModel.request(title: btn.title ?? "")
        }
    }
    
    func moreClick(period: String, popView: UIView) {
        dPrint("点击了"+period)
        for btn in self.timesArray {
            if btn.buttonType != .normal {
                btn.title = period
                btn.isSelected = true
            }else {
                btn.isSelected = false
            }
        }
        viewModel.request(title: period)
        if let popView = PopView.popView(subView: popView) {
            popView.dismiss()
        }
    }
    
    ///刷新头部界面
    func reloadInterface() {
        let vol = viewModel.coinModel.vol
        let price = viewModel.coinModel.price
        let open = viewModel.coinModel.open
        let money = viewModel.coinModel.money
        
        self.volume.text = "\(Int(vol))"
        let lastPrice = CYCalculate.stringWithNum(num: NSNumber(value: price))
        self.lastPrice.text = lastPrice
        var per: Double = 0
        if open != 0 {
            per = fabs((price - open) * 100 / open)
        }
        var pers = String(format: "%0.2f", per)
        if price >= open {
            pers = "+\(pers)%"
            self.lastPrice.textColor = kGreenColor
            self.increase.textColor = kGreenColor
        }else {
            pers = "-\(pers)%"
            self.lastPrice.textColor = kRedColor
            self.increase.textColor = kRedColor
        }
        self.high.text = CYCalculate.stringWithNum(num: NSNumber(value: viewModel.coinModel.high))
        self.low.text = CYCalculate.stringWithNum(num: NSNumber(value: viewModel.coinModel.low))
        
        self.increase.text = pers
        
        let moneyStr = String(format: "%.2f", money)
        if AppCacheInfo.default.currency == "USD" {
            self.exchangeLastPrice.text = "≈$ \(moneyStr)"
        }else {
            self.exchangeLastPrice.text = "≈￥ \(moneyStr)"
        }
    }
}

extension KlineViewController: KlineViewModelDelegate {
    func socketTickDataChange() {
//        if let last = viewModel.dataArray.last  {
//            let h = CYCalculate.stringWithNum(num: NSNumber(value: last[2]))
//            let l = CYCalculate.stringWithNum(num: NSNumber(value: last[3]))
//            self.high.text = h
//            self.low.text = l
//        }
        if self.chatView.rangeTo == viewModel.dataArray.count - 1{
            self.chatView.reloadData(toPosition: .end, resetData: true)
        }else {
            self.chatView.reloadData()
        }
        self.reloadInterface()
    }
    func socketChartDataChange(isTimeLine: Bool) {
        self.socketTickDataChange()
        self.activityView.stopAnimating()
        if isTimeLine {
            self.chatView.setSerie(hidden: true, inSection: 0)
            self.chatView.setSerie(hidden: true, inSection: 1)
            self.chatView.setSerie(hidden: false, by: CHSeriesKey.timeline, inSection: 0)
            self.chatView.setSerie(hidden: false, by: "timelineMA", inSection: 0)
            self.chatView.setSerie(hidden: false, inSection: 1)
        }else {
            self.chatView.setSerie(hidden: true, inSection: 0)
            self.chatView.setSerie(hidden: true, inSection: 1)
            self.chatView.setSerie(hidden: false, by: CHSeriesKey.candle, inSection: 0)
            self.chatView.setSerie(hidden: false, by: "priceMA", inSection: 0)
            self.chatView.setSerie(hidden: false, inSection: 1)
        }
        self.chatView.reloadData(toPosition: .end, resetData: true)
    }
    func socketDataError() {
        self.activityView.stopAnimating()
    }
    
}

extension KlineViewController: PopViewDelegate {
    func willDismiss() {
        for btn in self.timesArray {
            btn.backgroundColor = UIColor.clear
        }
    }
}

